package com.zbkj.crmeb.task.plat;

import com.factory.TaskProcessEngineFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class PushProductTask implements ApplicationRunner {

    @Resource
    private Redisson redisson;
    private static String envValue;
    @Value("${spring.profiles.active}")
    public void setEnv(String env) {
        envValue = env;
    }

    private static final String LOCK_KEY = PushProductTask.class.getName();
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (Objects.equals(envValue,"test")||Objects.equals(envValue,"dev")){
            log.info("当前环境暂不推送商品, env:{}",envValue);
            return;
        }
        final AtomicInteger index = new AtomicInteger(0);
        // 整个线程轮询
        new Thread(()->{
            while (true){
                RLock rLock = redisson.getLock(LOCK_KEY);
                try {
                    if (!rLock.tryLock(3, TimeUnit.SECONDS)){
                        log.warn("未获取到锁，稍后尝试");
                        continue;
                    }
                    log.error("推送商品到平台,第{}次数", index.getAndIncrement());
                    TaskProcessEngineFactory.executeTask();
                    Thread.sleep(RandomUtils.nextInt(100,1000));
                }catch (Exception e){
                    log.error("商品轮询任务执行失败");
                }finally {
                    // 解锁
                    rLock.unlock();
                }
            }
        }).start();
    }
}
